<template>
  <view class="publish-view">
    <!-- 提示信息弹窗 -->
    <uni-popup ref="message" type="message">
      <uni-popup-message :type="data.msgType" :message="data.messageText" :duration="2000"></uni-popup-message>
    </uni-popup>
      <scroll-view scroll-y="true" class="publish-trip-box">
        <!-- 添加图片区域 -->
         <scroll-view scroll-x="true" class="img-list-box" show-scrollbar="false">
           <view class="img-list">
              <view class="img-item" v-for="(item,index) in data.imgList" :key="index">
                <view class="img-num">{{index+1}}</view>
                <view class="del-img" @click="delImgList(index)">×</view>
                <image class="pub-img" :src="item.url" mode="aspectFill"></image> 
              </view>
               <view class="img-item" v-for="(item,index) in data.uploadImgList" :key="index">
                 <view class="img-num">{{data.imgList.length+index+1}}</view>
                 <view class="del-img" @click="delUploadImg(index)">×</view>
                 <image class="pub-img" :src="item" mode="aspectFill"></image> 
               </view>
             <view style="padding-right: 10px;">
               <view class="add-img" @click="addImg">
                 <text>+</text>
               </view>
             </view>
           </view>
         </scroll-view>
         <!-- 标题区域 -->
         <view class="trip-new-log">
           <view class="trip-index"></view>
           标题
         </view>
         <view class="input-title">
           <input v-model="data.title" class="p-input" type="text" placeholder="标题内容(50)" maxlength="50"/>
         </view>
         <view class="trip-new-log">
           <view class="trip-index"></view>
           出发地-目的地
         </view>
         <!-- 出发地和目的地选择 -->
         <view>
           <view class="place-box">
             <picker mode="multiSelector" @change="bindMultiPickerChangeDeparture" @columnchange="bindMultiPickerColumnChangeDeparture" :value="data.departureIndex" :range="data.departure" range-key="label">
               <view class="place-item" style="font-size: 18px;color: black;" v-if="data.departureId != ''">{{data.placeList[data.departureIndex[0]].label}}-{{data.placeList[data.departureIndex[0]].cityList[data.departureIndex[1]].label}}</view>
               <view class="place-item" v-if="data.departureId == ''">{{data.departureName}}</view>
             </picker>
             <view>———▶</view>
             <picker mode="multiSelector" @change="bindMultiPickerChangeDestination" @columnchange="bindMultiPickerColumnChangeDestination" :value="data.destinationIndex" :range="data.destination" range-key="label">
               <view class="place-item" style="font-size: 18px;color: black;" v-if="data.destinationId != ''">{{data.placeList[data.destinationIndex[0]].label}}-{{data.placeList[data.destinationIndex[0]].cityList[data.destinationIndex[1]].label}}</view>
               <view class="place-item" v-if="data.destinationId == ''">{{data.destinationName}}</view>
             </picker>
           </view>
         </view>
         <view class="trip-new-log">
           <view class="trip-index"></view>
           出发时间-天数
         </view>
         <view class="start-day-box">
           <picker mode="date" :value="date" :start="startDate" :end="endDate" @change="bindDateChange">
             <view v-if="data.date!=''" style="font-size: 18px;">{{data.date}}</view>
             <view v-else style="color: #949494;font-size: 18px;">请选择出发时间</view>
           </picker>
           <!-- 天数选择 -->
           <view>---</view>
           <picker @change="bindPickerChange" :value="data.dayIndex" :range="data.dayList">
             <view v-if="data.dayIndex!=''" style="font-size: 18px;">{{data.dayList[data.dayIndex]}}天</view>
             <view v-else style="color: #949494;font-size: 18px;">请选择天数</view>
           </picker>
         </view>
         <!-- 行程 -->
         <view class="trip-new-log">
           <view class="trip-index"></view>
           行程
         </view>
         <!-- 内容区域 -->
         <view class="content-view">
           <view class="content-box">
             <textarea class="content-textarea" v-model="data.content" @blur="bindTextAreaBlur" auto-height placeholder="填写行程..." maxlength="1000"/>
           </view>
         </view>
         <!-- 说明 -->
         <view class="trip-new-log">
           <view class="trip-index"></view>
           说明
         </view>
         <!-- 内容区域 -->
        <view class="content-view">
           <view class="content-box">
             <textarea class="content-textarea" v-model="data.explain" @blur="bindTextAreaBlur" auto-height placeholder="填写说明..." maxlength="1000"/>
           </view>
         </view>
      </scroll-view>
    
    <!-- 底部操作栏 -->
    <view class="pub-tool-box">
      <view class="draft-box" @click="saveDraft">
        <image class="draft-img" src="../../static/img/draft.png"></image>
        <text class="draft-text">存草稿</text>
      </view>
      <button class="p-button" @click="publishTripNew">发布资讯</button>
    </view>
  </view>
</template>

<script setup>
import { reactive, ref,toRefs,computed } from 'vue';
import { onShow,onLoad } from '@dcloudio/uni-app'
import helper from '../../common/helper.js'

const currentDate = getMyDate({
    format: true
})

const data = reactive({
  title:"",
  content:"",
  explain:"",
  imgList:[],
  tripNewId: "",
  tripNew:{},
  dayList:[2,3,4,5,6,7,8,9,10,11,12,13,14],
  dayIndex:"",
  departure:[],
  departureIndex: [0,0],
  departureId: "",
  destination:[],
  destinationIndex: [0,0],
  destinationId: "",
  departureName:"请选择出发地",
  destinationName:"请选择目的地",
  date:"",
  placeList:[],
  childArr:[],
  msgType:"",
  messageText:"",
  uploadImgList:[],
  deleteImgId:[],
  uploadImgId:[],
});

const message = ref(null)

function messageToggle(type,text) {
  data.msgType = type
  data.messageText = text
  message.value.open()
}

onLoad((options)=>{
  console.log('onLoad发布资讯'+options)
  if(options.tripNewId != null){
    data.tripNewId = options.tripNewId
    getTripNewDetail()
  }
  getPlace()
})

async function getTripNewDetail(){
  let res = await helper.getTripNewDetailReq(data.tripNewId)
  if(res.data.code == 200){
    data.tripNew = res.data.data
    data.tripNew.startTime = helper.getDate(data.tripNew.startTime)
    data.title = data.tripNew.title
    data.content = data.tripNew.journey
    data.explain = data.tripNew.explain
    data.dayIndex = data.tripNew.dayNum - 2
    data.date = data.tripNew.startTime
    data.imgList = data.tripNew.imgList
  }
}

function getPlace(){
  uni.request({
      url: helper.webUrl + "/tripNew/getPlace",
      method:'GET',
      success: (res) => {
        console.log(res.data);
        data.placeList = res.data.data
        for (let i = 0; i < data.placeList.length; i++) {
          // 将数据源中的二级分类 push 进 childArr，作为二级分类的数据源
          data.childArr.push(data.placeList[i].cityList)
          if(data.tripNewId != ""){
            data.departureId = data.tripNew.departureId
            data.destinationId = data.tripNew.destinationId
            for(let j = 0; j < data.placeList[i].cityList.length; j++){
              if(data.placeList[i].cityList[j].id == data.tripNew.departureId){
                data.departureIndex = [i,j]
              }
              if(data.placeList[i].cityList[j].id == data.tripNew.destinationId){
                data.destinationIndex = [i,j]
              }
            }
          }
        }; 
        // 一级分类的数据源
        data.departure[0] = data.placeList
        data.destination[0] = data.placeList
        if(data.tripNewId != ""){
          data.departure[1] = data.childArr[data.departureIndex[0]]
          data.destination[1] = data.childArr[data.destinationIndex[0]]
        }else{
          // 第一次打开时，默认给一级分类添加它的二级分类
          data.departure[1] = data.childArr[0]
          data.destination[1] = data.childArr[0]
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
      }
    })
}

function bindMultiPickerChangeDeparture(e){
  console.log('出发地改变，携带值为', e.detail.value)
  data.departureId = data.placeList[e.detail.value[0]].cityList[e.detail.value[1]].id
  console.log(data.departureId)
}

function bindMultiPickerColumnChangeDeparture(e){
  if(!data.departureIndex || !data.departureIndex.length){
  		data.departureIndex = [0,0]
  	}
  	
  	let column = e.detail.column;
  	let value = e.detail.value;
  	console.log(column , value);
  	
  	let departureIndex = data.departureIndex;
  	departureIndex[column] = value;
  	if(column == 0){
  		departureIndex[1] = 0;
  	}
  	data.departureIndex = departureIndex;
  	
  	let departure = [];
  	departure[0] = data.placeList;
  	departure[1] = data.placeList[departureIndex[0]].cityList;
  	data.departure = departure;
}

function bindMultiPickerColumnChangeDestination(e){
  if(!data.destinationIndex || !data.destinationIndex.length){
  		data.destinationIndex = [0,0]
  	}
  	
  	let column = e.detail.column;
  	let value = e.detail.value;
  	console.log(column , value);
  	
  	let destinationIndex = data.destinationIndex;
  	destinationIndex[column] = value;
  	if(column == 0){
  		destinationIndex[1] = 0;
  	}
  	data.destinationIndex = destinationIndex;
  	
  	let destination = [];
  	destination[0] = data.placeList;
  	destination[1] = data.placeList[destinationIndex[0]].cityList;
  	data.destination = destination;
}

function bindMultiPickerChangeDestination(e){
  console.log('目的地改变，携带值为', e.detail.value)
  data.destinationId = data.placeList[e.detail.value[0]].cityList[e.detail.value[1]].id
  console.log(data.destinationId)
}

function bindPickerChange(e) {
  console.log('天数picker发送选择改变，携带值为', e.detail.value)
  data.dayIndex = e.detail.value
}

function bindDateChange(e) {
  data.date = e.detail.value
}

function bindTextAreaBlur(e) {
  console.log(e.detail.value)
}

let startDate = computed(()=>{
  return getMyDate('start');
});

let endDate = computed(()=>{
  return getMyDate('end');
})

function getMyDate(type) {
  const date = new Date();
  let year = date.getFullYear();
  let month = date.getMonth() + 1;
  let day = date.getDate()

  if (type === 'start') {
      year = year;
  } else if (type === 'end') {
      year = year + 2;
  }
  month = month > 9 ? month : '0' + month;
  day = day > 9 ? day : '0' + day;
  return `${year}-${month}-${day}`;
}

function saveDraft(){
  console.log("存入草稿")
}

async function publishTripNew(){
  console.log("发布资讯")
  //判断内容是否为空
  if(data.title == null || data.title.trim() == ''){
    messageToggle("info","标题不能为空！")
    return
  }
  if(data.content == null || data.content.trim() == ''){
    messageToggle("info","行程不能为空！")
    return
  }
  if(data.imgList.length == 0 && data.uploadImgList.length == 0){
    messageToggle("info","图片不能为空！")
    return
  }
  if(data.dayIndex == null || data.title.trim() == ''){
    messageToggle("info","出行天数不能为空！")
    return
  }
  if(data.departureIndex == '' || data.destinationIndex == ''){
    messageToggle("info","地点不能为空！")
    return
  }
  if(data.date == ''){
    messageToggle("info","出发时间不能为空！")
    return
  }
  if(data.explain == ''){
    messageToggle("info","说明不能为空！")
    return
  }
  
  if(data.tripNewId == ""){
    let result1 = await publishTripNewReq()
    console.log(result1.data)
    if(result1.data.code == 200){
      for(let i = 0; i < data.uploadImgList.length; i++){
        const result2 = await uploadTripNewImage(data.tripNewId,i)
        console.log(result2)
        let res2 = JSON.parse(result2.data)
        if(res2.code == 200){
          data.uploadImgId.push(res2.data)
        }else{
          messageToggle("info",res2.msg)
          if(data.uploadImgId.length > 0){
            deleteTripNewImage(data.uploadImgId)
          }
          helper.deleteTripNewReq(data.tripNewId)
          data.tripNewId = ""
          return
        }
      }
      uni.navigateBack()
    }else{
      messageToggle("info","发布失败/(ㄒoㄒ)/~~")
    }
  }else{
    //编辑资讯
    for(let i = 0; i < data.uploadImgList.length; i++){
      const result2 = await uploadTripNewImage(data.tripNewId,i)
      console.log(result2)
      let res2 = JSON.parse(result2.data)
      if(res2.code == 200){
        data.uploadImgId.push(res2.data)
      }else{
        messageToggle("info",res2.msg)
        if(data.uploadImgId.length > 0){
          deleteTripNewImage(data.uploadImgId)
        }
        return
      }
    }
    
    let res = await updateTripNew()
    if(res.data.code == 200){
      uni.navigateBack()
    }else{
      messageToggle("info","发布失败!")
      if(data.uploadImgId.length > 0){
        deleteTripNewImage(data.uploadImgId)
      }
    } 
  } 
}

function publishTripNewReq(){
  return new Promise((resolve, reject) => {
    uni.request({
          url: helper.webUrl+'/tripNew/addTripNew', 
          method:'POST',
          header: {
              'Content-Type': 'application/json' ,//自定义请求头信息
              'token': helper.getToken()
          },
          data: {
            title: data.title,
            journey: data.content,
            departureId: data.departureId,
            destinationId: data.destinationId,
            dayNum: data.dayList[data.dayIndex],
            startTime: data.date,
            explain: data.explain
          },
          success: (res) => {
            console.log(res.data);
            if(res.data.code == 200){
              data.tripNewId = res.data.data.id
              resolve(res)
            }else{
              messageToggle("info",res.data.msg)
            }
          },
          fail: (err) => {
            console.error('请求失败:', err);
          }
      });
  });   
}

function uploadTripNewImage(tripNewId,i){
  return new Promise((resolve, reject) => {
      uni.uploadFile({
        url: helper.webUrl + '/tripNew/uploadTripNewImg',
        filePath: data.uploadImgList[i],
        name: 'file',
        formData:{
          'tripNewId': tripNewId,
          'imageIndex': data.imgList.length + i + 1
        },
        success:(res) =>{
          console.log(res.data);  
          resolve(res)
        },
        fail: (err) => {
          messageToggle("info","上传失败")
          console.error('上传失败:', err);
        },
        complete: (completeRes) => {
          console.log('上传完成, 状态:', completeRes.statusCode);
        }
      })
  });   
}

function updateTripNew(){
  return new Promise((resolve, reject) => {
    uni.request({
          url: helper.webUrl+'/tripNew/updateTripNew', 
          method:'POST',
          header: {
              'Content-Type': 'application/json' ,//自定义请求头信息
          },
          data: {
            id: data.tripNewId,
            title: data.title,
            journey: data.content,
            departureId: data.departureId,
            destinationId: data.destinationId,
            dayNum: data.dayList[data.dayIndex],
            startTime: data.date,
            explain: data.explain,
            tripNewImageIdList: data.deleteImgId,
          },
          success: (res) => {
            console.log(res.data);
            resolve(res)
          },
          fail: (err) => {
            console.error('请求失败:', err);
          }
      });
  });   
}

function deleteTripNewImage(idList){
  return new Promise((resolve, reject) => {
    uni.request({
          url: helper.webUrl+'/tripNew/deleteTripNewImage', 
          method:'POST',
          header: {
            'Content-Type': 'application/json' //自定义请求头信息,
          },
          data: {
            tripNewImageIdList: idList
          },
          success: (res) => {
            console.log(res.data);
            resolve(res)
          },
          fail: (err) => {
            console.error('请求失败:', err);
          }
      });
  });   
}

function delUploadImg(index){
  console.log("删除上传照片"+index)
  data.uploadImgList.splice(index,1)
}

function delImgList(index){
  console.log("删除原有照片"+index)
  data.deleteImgId.push(data.imgList[index].id)
  data.imgList.splice(index,1)
}

function addImg(){
  console.log("添加图片")
  uni.chooseImage({
  	count: 6, //默认9
  	sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
  	sourceType: ['album'], //从相册选择
  	success: function (res) {
  		console.log(JSON.stringify(res));
      for(let i = 0; i < res.tempFilePaths.length; i++){
        data.uploadImgList.push(res.tempFilePaths[i])
      }
      console.log(data.uploadImgList)
  	}
  });
}

</script>

<style>
.publish-view{
  width: 100vw;
  height: 100vh;
  background-color: #fff;
}
.publish-trip-box{
  width: 100vw;
  height: 92vh;
}
.img-list-box{
  width: 100vw;
  height: 20vh;
  background-color: #fff;
  white-space: nowrap;
  border-bottom: 1px solid #c5c5c5;
}
.img-list{
  display: flex;
  padding: 15px;
}
.img-item{
  width: 100px;
  height: 100px;
  border-radius: 10px;
  margin: 5px;
}
.pub-img{
  width: 100px;
  height: 100px;
  border-radius: 10px;
}
.img-num{
  position: absolute;
  padding: 5px;
  background-color: red;
  border-bottom-right-radius: 10px;
  border-top-left-radius: 10px;
  background-color: rgba(0, 0, 0, 0.5);
  color: #fff;
}
.del-img{
  position: absolute;
  background-color: #89C0FF;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  color: #fff;
  display: flex;
  margin-left: 80px;
  justify-content: center;
}
.add-img{
  margin: 5px;
  width: 100px;
  height: 100px;
  border-radius: 10px;
  background-color: #EBEBEB;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 30px;
  color: #949494;
}
.input-title{
  width: 100vw;
  height: 7vh;
  background-color: #fff;
  display: flex;
  align-items: center;
  padding-left: 20px;
  border-bottom: 1px solid #c5c5c5;
}
.p-input{
  font-size: 18px;
  width: 100%;
}
.trip-new-log{
  width: 100vw;
  height: 6vh;
  font-size: 20px;
  display: flex;
  align-items: center;
  padding-left: 10px;
  font-weight: bold;
}
.trip-index{
  width:5px;
  height: 20px;
  background-color: #89C0FF;
  margin-right: 10px;
}
.start-day-box{
  display: flex;
  padding-left: 20px;
}
.place-box{
  display: flex;
}
.place-item{
  font-size: 18px;
  padding-inline: 20px;
  color: #949494;
}
.content-view{
  width: 100vw;
  background-color: #fff;
}
.content-box{
  width: 95%;
  display: flex;
  margin: auto;
  padding-top: 8px;
}
.content-textarea{
  width: 100%;
  min-height: 30vh;
  font-size: 18px;
}
.pub-tool-box{
  position: absolute;
  bottom: 0;
  width: 100vw;
  height: 8vh;
  background-color: #fff;
  display: flex;
}
.draft-box{
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  margin-left: 30px;
}
.draft-img{
  width: 30px;
  height: 30px;
}
.p-button{
  width: 60%;
  background-color: #89C0FF;
  color: #fff;
  font-size: 16px;
  border-radius: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: auto;
}
</style>

